<template>
  <div>
  <!-- 侧边悬浮-在线对话 Start -->
  <div class="g-layside-chat" >
    <a class="m-layside-chatbox" href="javascript:;" v-on:click="talkWin" id="liaoitian_talk">
      <i class="icon iconfont icon-duiHuaKuang left"></i>
      <em class="left">在线对话</em>
      <span v-if="num>0" class="left num" id="leftnum" style="">{{num}}</span>
    </a>
  </div>
  <!-- 侧边悬浮-在线对话 End -->

  <!--聊天窗口-->
<div class="qqBox" v-if="isshow">
	<div class="BoxHead">
		<div class="headImg">
			<img v-bind:src="avatar" id="userPicTalk"/>
		</div>
		<div class="internetName" id="userNameTalk">{{nickname}}</div>
		<a class="talkClose" href="javascript:;" v-on:click="guanbiTalk">
			<i class="icon iconfont icon-guanbi"></i>
		</a>
	</div>
	<div class="context">
		<div class="conLeft">
			<ul id="ullist">
          <li v-for="(value, i) in huihua" v-on:click="chatTalk(value.extra,i)"  v-bind:class="{bg:value.nowMemberid == value.memberid}">
              <div class="liLeft" ><img v-bind:src="value.avatar" width="43px" height="41px" style="border-radius:20px;" /></div>
             <div class="liRight">
                  <span class="intername">{{value.nickname}}</span>
                  <span v-if="value.messageName=='ImageMessage'" class="infor">[图片]</span>
                  <span v-else-if="value.messageName=='LocationMessage'" class="infor">[位置]</span>
                  <span v-else class="infor">{{value.content}}</span>
              </div>
            <div v-if="value.unreadMessageCount!=0 && value.nowMemberid != value.memberid && value.ismine==1" class="redwei">{{value.unreadMessageCount}}</div>
          </li>
			</ul>
		</div>
     <div class="conRight" id="talk_with" v-if="nowMemberid!=0">

    			<div class="Righthead">
    				<div class="headName"></div>
    				<div class="headConfig">
    				</div>
    			</div>
    			<div class="RightCont">
    				<ul class="newsList">
						<div style="text-align: center;padding: 10px" id="gengsuoid"><a href="javascript:;" style="color: #999999">点击加载更多聊天</a></div>
    				</ul>
    			</div>
    			<div class="RightFoot">
    				<div class="emjon">
    					<ul id="emjonbox" onclick="">

    					</ul>
    				</div>
    				<div class="footTop">
    					<ul>
    						<li class="ExP"><img src="images/20170926103645_33.jpg"/></li>
    						<li><img src="images/20170926103645_41.jpg" id="inputimg" alt="" />
							<input type="file" id="fileinput" style="display: none"  >
							</li>
    					</ul>
    				</div>
    				<div class="inputBox">
    					<textarea id="dope" style="width: 99%;height: 75px; border: none;outline: none;resize: none;" name="" rows="" cols=""></textarea>
    					<button class="sendBtn" id="sendBtn" >发送(s)</button>
    				</div>
    			</div>

    	</div>
	</div>
</div>
  </div>
</template>

<script>
  export default {
    name: 'SuspendTalk',
    props:['pro','nowTalkid','nickname','isshow','avatar'],
    data () {
      return {num:0};
    },
    created:function(){

      var _this=this;//本组件对象

      //当前聊天人
      _this.nowMemberid =_this.nowTalkid?_this.nowTalkid:0;

      $.post(this.GLOBAL.base_url+'/yiAppWeb/getToken',{id:this.GLOBAL.uid,token:this.GLOBAL.token},function (res) {
        if(res.code==200){
          var talk_token = res.token;
          //初始化聊天服务器
          RongIMLib.RongIMClient.init(res.appkey);
          // 设置监听器
          RongIMClient.setConnectionStatusListener({
            onChanged: function (status) {
              switch (status) {
                case RongIMLib.ConnectionStatus.CONNECTED:
                  console.log('链接成功');
                  break;
                case RongIMLib.ConnectionStatus.CONNECTING:
                  console.log('正在链接');
                  break;
                case RongIMLib.ConnectionStatus.DISCONNECTED:
                  console.log('断开连接');
                  break;
                case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
                  console.log('其他设备登录');
                  break;
                case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
                  console.log('域名不正确');
                  break;
                case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
                  console.log('网络不可用');
                  break;
              }
            }});

          // 消息监听器
          RongIMClient.setOnReceiveMessageListener({
            // 接收到的消息
            onReceived: function (message) {
              // 判断消息类型
              switch(message.messageType){
                case RongIMClient.MessageType.TextMessage:
                  console.log(message);

                  if(message.senderUserId==_this.nowMemberid){//正在聊
                    // histy(nowMemberid);//记录不同步
                    var extra = message.content.extra;
                    extra = extra.replace(/\n/g,"\\\\n").replace(/\r/g,"\\\\r");
                    extra = JSON.parse(extra);
                    var html = '<li>' +
                      '<div class="nesHead">' +
                      '<img src="'+extra.mavatar+'">' +
                      '</div>' +
                      '<div class="news" style="height: auto">' +
                      '<img class="jiao" src="images/jiao.jpg"> ' +
                      TextZhuanimg(message.content.content)+
                      '</div>' +
                      '</li>';
                    $('.newsList').append(html);
                    $(".RightCont").scrollTop($('.RightCont')[0].scrollHeight);
                  }else{//和其他人聊
                    huihua();
                  }
                  break;
                case RongIMClient.MessageType.VoiceMessage:
                  // 对声音进行预加载
                  // message.content.content 格式为 AMR 格式的 base64 码
                  break;
                case RongIMClient.MessageType.ImageMessage:
                  // message.content.content => 图片缩略图 base64。
                  // message.content.imageUri => 原图 URL。
                  break;
                case RongIMClient.MessageType.DiscussionNotificationMessage:
                  // message.content.extension => 讨论组中的人员。
                  break;
                case RongIMClient.MessageType.LocationMessage:
                  // message.content.latiude => 纬度。
                  // message.content.longitude => 经度。
                  // message.content.content => 位置图片 base64。
                  break;
                case RongIMClient.MessageType.RichContentMessage:
                  // message.content.content => 文本消息内容。
                  // message.content.imageUri => 图片 base64。
                  // message.content.url => 原图 URL。
                  break;
                case RongIMClient.MessageType.InformationNotificationMessage:
                  // do something...
                  break;
                case RongIMClient.MessageType.ContactNotificationMessage:
                  // do something...
                  break;
                case RongIMClient.MessageType.ProfileNotificationMessage:
                  // do something...
                  break;
                case RongIMClient.MessageType.CommandNotificationMessage:
                  // do something...
                  break;
                case RongIMClient.MessageType.CommandMessage:
                  // do something...
                  break;
                case RongIMClient.MessageType.UnknownMessage:
                  // do something...
                  break;
                default:
                // do something...
              }
            }
          });

          // 连接服务器
          RongIMClient.connect(talk_token, {
            onSuccess: function(userId) {
              _this.talk_count_wei();
              _this.huihuaList();
              console.log("Connect successfully." + userId);
            },
            onTokenIncorrect: function() {
              console.log('token无效');
            },
            onError:function(errorCode){
              var info = '';
              switch (errorCode) {
                case RongIMLib.ErrorCode.TIMEOUT:
                  info = '超时';
                  break;
                case RongIMLib.ConnectionState.UNACCEPTABLE_PAROTOCOL_VERSION:
                  info = '不可接受的协议版本';
                  break;
                case RongIMLib.ConnectionState.IDENTIFIER_REJECTED:
                  info = 'appkey不正确';
                  break;
                case RongIMLib.ConnectionState.SERVER_UNAVAILABLE:
                  info = '服务器不可用';
                  break;
              }
              console.log(errorCode);
            }
          });
        }
      },'json')

    },
    methods:{
      huihua:function (event) {
        alert(1);
      },
      //聊天窗口状态
      talkWin:function(){
        if(this.isshow){
          this.$emit("talkWinIsshow",false);
        }else{
          this.$emit("talkWinIsshow",true);
        }
      },
      //聊天内容
      chatTalk:function (extra,i) {
        console.log(extra);
        console.log(i);
        $('#talk_with').css('display','-webkit-box');
        extra = extra.replace(/\n/g,"\\\\n").replace(/\r/g,"\\\\r");
        var extra_arr = JSON.parse(extra);
        var arr = {'nickname':extra_arr.nickname,'extra':extra};
        this.mineavaer=extra_arr.mavatar;
        this.now_extra_arr = extra_arr;
        // var html = template('huihuaDetil', arr);
        // $("#talk_with").html(html);
        histy(extra_arr.memberid);
        this.nowMemberid = extra_arr.memberid;
        //绑定图片上传
        $('#inputimg').click(function () {
          $("#fileinput").click();
        })

        if(i!=undefined){
          $("#ullist li").each(function (index ,val) {
            if(index==i){
              $(this).addClass("bg");
            }else{
              $(this).removeClass('bg');
            }
          })
        }


        var html = '';
        for(var j=1;j<=105;j++){
          html+='<img src="'+page_url+'images/emotion/Expression_'+j+'.png" style="width: 24px;height: 24px">';
        }
        $("#emjonbox").html(html);
        //绑定选择表情事件
        $("#emjonbox img").click(function () {
          var jilu = $("#dope").val();
          console.log($(this).prop("outerHTML"));
          jilu+=this.imgZhuanText($(this).prop("outerHTML"));
          $("#dope").val(jilu);
          $(".emjon").hide();
          $("#dope").focus();
        })

        //聊天框输入键盘确定键
        $("#dope").keydown(function (event) {
          if (event.keyCode == 13 && event.shiftKey) {
            // $("#dope").val($("#dope").val()+'&#10;');
            // $("#sendBtn").click();
          }else if (event.keyCode == 13) {
            $("#sendBtn").click();
            event.preventDefault();
          }
        });
      },
      //图片转义文字
      imgZhuanText:function (str) {
        // var str = "<img class='expression' src='api.wgtRootDir/res/chatBox/emotion/Expression_105.png' /><img class='expression' src='api.wgtRootDir/res/chatBox/emotion/Expression_98.png' />hehe";
        var txt = str.replace(/\<(.*?)\>/gm,
          function(match) {
            var emotionArr = match.match(/Expression_\d{1,3}/);
            return biaoqingE[emotionArr[0]];
          });
        return txt;
      },
      //会话列表
      huihuaList:function ()
      {
        var _this = this;
        RongIMLib.RongIMClient.getInstance().getConversationList({
          onSuccess: function(list) {
            console.log(list);
            var extra = [];
            for (var i = 0; i < list.length; i++) {

              extra[i] = JSON.parse( list[i]['latestMessage']['content']['extra'] );
              //转义表情图片
              if(list[i]['latestMessage']['content']['messageName']=='TextMessage'){
                extra[i]['content']=list[i]['latestMessage']['content']['content'].trim();
              }
              if (list[i]['latestMessage']['senderUserId'] == list[i]['targetId']) {//最后一条记录是对方发的
                extra[i] = {
                  nickname:extra[i]['mname'],
                  avatar:extra[i]['mavatar'],
                  memberid:extra[i]['mid'],
                  mname:extra[i]['nickname'],
                  mavatar:extra[i]['avatar'],
                  mid:extra[i]['memberid'],
                  content:extra[i]['content'],
                  messageName:list[i]['latestMessage']['content']['messageName'],
                  nowMemberid:_this.nowMemberid,
                  unreadMessageCount:list[i]['unreadMessageCount'],
                  ismine:1
                };
                extra[i]['extra'] = _this.imgZhuanText(JSON.stringify(extra[i]));
              } else {
                extra[i]['content'] = list[i]['latestMessage']['content']['content'].trim();
                extra[i]['messageName']=list[i]['latestMessage']['content']['messageName'];
                extra[i]['extra'] = JSON.stringify(extra[i]);
              }
            }
            _this.huihua = extra;
          },
          onError: function(error) {
            // do something...
          }
        },null);
      },
      //会话总未读数
       talk_count_wei:function() {
        var _this = this;
        RongIMLib.RongIMClient.getInstance().getConversationList({
          onSuccess: function(list) {
            var extra = 0;
            for (var i = 0; i < list.length; i++) {
              extra += list[i]['unreadMessageCount'];
            }
            _this.num=extra;
          },
          onError: function(error) {
            // do something...
          }
        },null);
      },
      guanbiTalk:function () {
        this.$emit("talkWinIsshow",false);
      }
    }

  }
</script>
<style scoped>
  .redwei{
    background-color: #e83535;
    width: 20px;
    height: 20px;
    position: absolute;
    right: 10px;
    top: 6px;
    border-radius: 40px;
    line-height: 20px;
    color: white;
    text-align: center;
    font-size: 8px;
  }
  #ullist li{
    position: relative;
  }
  .talkClose{
    position: absolute;
    right: 0;
    top: 8px;
    padding: 0 16px;
    color: #fff;
    font-size: 22px;
    text-align: center;
  }
  .imgEmj{
    width: 24px;
    height: 24px;
    margin-bottom: -6px;
  }
  .sentTime{
    text-align: center;
  }
  .sentTime span{
    color: white;
    padding: 5px 11px;
    background-color: #797f78;
    filter: alpha(opacity=50);
    opacity: 0.3;
    border-radius: 14px;
  }
</style>
